//
//  comBlueboxmoonPhoneMACLookup.m
//  MACLookup
//
//  Created by Daniel Hazelbaker on 4/3/09.
//  Copyright 2009 High Desert Church. All rights reserved.
//

#import "comBlueboxmoonPhoneMACLookup.h"
#import "comBlueboxmoonPhoneMACLookupFormatter.h"


@implementation comBlueboxmoonPhoneMACLookup


//
// Retrieve my preferences, this is a read-only procedure.
//
- (NSDictionary *)myPreferences
{
    return [[pluginController preferences] valueForKey:kMACLookupPreferenceKey];
}


//
// Set the default preferences.
//
- (void)setDefaultPreferences
{
    NSMutableDictionary	*dict;
    id			prefs = [pluginController preferences];


    dict = [[[prefs valueForKey:kMACLookupPreferenceKey] mutableCopy] autorelease];
    if (dict == nil)
	dict = [NSMutableDictionary dictionary];

    if ([dict valueForKey:kMACLookupMacAddressKey] == nil)
	[dict setValue:@"00:00:00:00:00:00" forKey:kMACLookupMacAddressKey];

    [prefs setValue:dict forKey:kMACLookupPreferenceKey];
}



#pragma mark BMPluginProtocol
//////////////////////////////////////////////////////////////////////////
//
// BMPluginProtocol
//
//////////////////////////////////////////////////////////////////////////


//
// Retrieve the handlers this plugin provides.
//
- (NSArray *)availableHandlersForPluginController:(BMPluginController *)controller
{
    pluginController = controller;

    //
    // Load the preference view if we need to.
    //
    if (mainView == nil) {
	[self setDefaultPreferences];
	[NSBundle loadNibNamed:@"preferences" owner:self];
	[macAddressField setFormatter:[[[comBlueboxmoonPhoneMACLookupFormatter alloc] init] autorelease]];
    }

    return [NSArray arrayWithObject:[NSDictionary dictionaryWithObjectsAndKeys:
		[[NSBundle bundleForClass:[self class]] bundleIdentifier], kPluginHandlerIDKey,
		@"MAC Address", kPluginHandlerNameKey,
		@"Attempts to lookup the phone's IP address by providing its MAC address.", kPluginHandlerDescriptionKey,
		self, kPluginHandlerObjectKey,
		[NSNumber numberWithInt:BMPluginAddressHandler], kPluginHandlerTypeKey,
		self, kPluginHandlerPreferencesKey,
		nil]];
}



#pragma mark BMPluginHandlerProtocol
//////////////////////////////////////////////////////////////////////////
//
// BMPluginHandlerProtocol
//
//////////////////////////////////////////////////////////////////////////


//
// The phone address lookup continues until the first plugin returns a
// non-nil result, indicating that it found the IP address (or host name)
// we are looking for.
//
- (NSString *)lookupPhoneAddress
{
    NSString	    *ipAddress, *address;
    int		    i;


    address = [[self myPreferences] valueForKey:kMACLookupMacAddressKey];
    if ([address length] != 0) {
	for (i = 0; i < MACADDRESS_LOOKUP_TRIES; i++) {
	    NSFileHandle	*readHandle;
	    NSTask		*task;
	    NSPipe		*pipe;
	    NSData		*data;

	    //
	    // Setup the task.
	    //
	    pipe = [NSPipe pipe];
	    readHandle = [pipe fileHandleForReading];
	    task = [[[NSTask alloc] init] autorelease];
	    [task setLaunchPath:[[[NSBundle bundleForClass:[self class]] resourcePath] stringByAppendingPathComponent:@"findIPFromMac.sh"]];
	    [task setArguments:[NSArray arrayWithObject:address]];
	    [task setStandardInput:[NSPipe pipe]];
	    [task setStandardError:[NSPipe pipe]];
	    [task setStandardOutput:pipe];

	    //
	    // Launch the task and wait for it to finish.
	    //
	    [task launch];
	    while ([task isRunning] == YES) {
		[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
	    }

	    //
	    // Get the result.
	    //
	    data = [readHandle readDataToEndOfFile];
	    if ([data length] > 4) {
		ipAddress = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
		ipAddress = [ipAddress substringToIndex:([ipAddress length] - 1)];
		NSLog(@"Found %@ from %@", ipAddress, address);

		return ipAddress;
	    }
	}
    }

    return nil;
}


#pragma mark BMPluginPreferenceProtocol
//////////////////////////////////////////////////////////////////////////
//
// BMPluginPreferenceProtocol
//
//////////////////////////////////////////////////////////////////////////


- (NSView *)mainView
{
    return mainView;
}


//
// Load preferences.
//
- (void)willSelect
{
    //
    // Store the preferences.
    //
    [self setValue:[[[[pluginController preferences] valueForKey:kMACLookupPreferenceKey] mutableCopy] autorelease] forKey:@"preferences"];
}


//
// Save preferences.
//
- (void)didUnselect
{
    //
    // Save the preferences.
    //
    [[pluginController preferences] setValue:preferences forKey:kMACLookupPreferenceKey];

    [self setValue:nil forKey:@"preferences"];
}


@end
